// 物理系统模块

class PhysicsEngine {
    constructor(canvas) {
        this.canvas = canvas;
        this.engine = null;
        this.world = null;
        this.render = null;
        this.balls = [];
        this.walls = [];
        this.nextBallLevel = 1;
        this.isDropping = false;
        this.particles = [];
        
        this.initPhysics();
    }

    // 初始化物理引擎
    initPhysics() {
        // 创建引擎
        this.engine = Matter.Engine.create();
        this.world = this.engine.world;
        
        // 设置重力
        this.engine.world.gravity.y = GAME_CONFIG.physics.gravity;
        
        // 创建容器边界
        this.createContainer();
        
        // 设置碰撞检测
        this.setupCollisionDetection();
    }

    // 创建容器边界
    createContainer() {
        const { width, height, x, y } = GAME_CONFIG.container;
        const wallThickness = 10;
        
        // 底部
        const bottom = Matter.Bodies.rectangle(
            x, y + wallThickness/2, 
            width, wallThickness, 
            { isStatic: true, label: 'wall' }
        );
        
        // 左侧
        const left = Matter.Bodies.rectangle(
            x - width/2 - wallThickness/2, y - height/2, 
            wallThickness, height, 
            { isStatic: true, label: 'wall' }
        );
        
        // 右侧
        const right = Matter.Bodies.rectangle(
            x + width/2 + wallThickness/2, y - height/2, 
            wallThickness, height, 
            { isStatic: true, label: 'wall' }
        );
        
        this.walls = [bottom, left, right];
        Matter.World.add(this.world, this.walls);
    }
    
    // 重新创建容器边界
    recreateContainer() {
        // 移除旧的边界
        if (this.walls.length > 0) {
            Matter.World.remove(this.world, this.walls);
        }
        
        // 创建新的边界
        this.createContainer();
    }

    // 设置碰撞检测
    setupCollisionDetection() {
        Matter.Events.on(this.engine, 'collisionStart', (event) => {
            const pairs = event.pairs;
            
            pairs.forEach(pair => {
                const { bodyA, bodyB } = pair;
                
                // 检查是否是球体碰撞
                if (bodyA.label === 'ball' && bodyB.label === 'ball') {
                    this.handleBallCollision(bodyA, bodyB);
                } else if ((bodyA.label === 'ball' && bodyB.label === 'wall') ||
                          (bodyA.label === 'wall' && bodyB.label === 'ball')) {
                    // 球体与墙壁碰撞
                    Utils.playSound('collision', 0.2);
                }
            });
        });
    }

    // 处理球体碰撞
    handleBallCollision(bodyA, bodyB) {
        const ballA = this.findBallByBody(bodyA);
        const ballB = this.findBallByBody(bodyB);
        
        if (!ballA || !ballB) return;
        
        // 播放碰撞音效
        Utils.playSound('collision', 0.3);
        
        // 检查是否可以合成
        if (Utils.canMerge(ballA, ballB)) {
            this.mergeBalls(ballA, ballB);
        }
    }

    // 根据物理体查找球体
    findBallByBody(body) {
        return this.balls.find(ball => ball.body === body);
    }

    // 合成球体
    mergeBalls(ballA, ballB) {
        const newLevel = ballA.level + 1;
        const mergeX = (ballA.body.position.x + ballB.body.position.x) / 2;
        const mergeY = (ballA.body.position.y + ballB.body.position.y) / 2;
        
        // 移除原有球体
        this.removeBall(ballA);
        this.removeBall(ballB);
        
        // 创建新球体
        if (newLevel <= 9) {
            const newBall = this.createBall(mergeX, mergeY, newLevel);
            this.addBall(newBall);
        }
        
        // 创建增强粒子效果
        const baseParticleCount = Math.min(8 + newLevel * 2, 20); // 根据等级增加粒子数
        const particles = Utils.createParticles(
            mergeX, mergeY, 
            Utils.getBallColor(newLevel), 
            baseParticleCount
        );
        this.particles.push(...particles);
        
        // 为高等级球体添加额外的庆祝粒子
        if (newLevel >= 7) {
            const celebrationParticles = Utils.createParticles(
                mergeX, mergeY,
                '#ffd700', // 金色庆祝粒子
                6
            );
            this.particles.push(...celebrationParticles);
        }
        
        // 播放合成音效
        Utils.playSound(`merge_${newLevel}`, 0.5);
        
        // 震动反馈
        Utils.vibrate(50);
        
        // 显示分数
        const score = Utils.getMergeScore(newLevel);
        Utils.showFloatingText(mergeX, mergeY - 30, `+${score}`, Utils.getBallColor(newLevel));
        
        // 触发合成事件
        this.onMerge && this.onMerge(newLevel, score, mergeX, mergeY);
    }

    // 创建球体
    createBall(x, y, level) {
        const radius = Utils.getBallSize(level);
        const color = Utils.getBallColor(level);
        
        const body = Matter.Bodies.circle(x, y, radius, {
            restitution: GAME_CONFIG.physics.restitution,
            friction: GAME_CONFIG.physics.friction,
            label: 'ball'
        });
        
        return {
            body: body,
            level: level,
            color: color,
            radius: radius,
            id: Date.now() + Math.random()
        };
    }

    // 添加球体到世界
    addBall(ball) {
        this.balls.push(ball);
        Matter.World.add(this.world, ball.body);
    }

    // 移除球体
    removeBall(ball) {
        const index = this.balls.indexOf(ball);
        if (index > -1) {
            this.balls.splice(index, 1);
            Matter.World.remove(this.world, ball.body);
        }
    }

    // 投放球体
    dropBall(x, level) {
        if (this.isDropping) return false;
        
        this.isDropping = true;
        
        // 限制投放区域
        const dropZone = GAME_CONFIG.gameplay.dropZone;
        const clampedX = Utils.clamp(x, dropZone.x, dropZone.x + dropZone.width);
        
        // 创建球体
        const ball = this.createBall(clampedX, dropZone.y, level || this.nextBallLevel);
        this.addBall(ball);
        
        // 播放投放音效
        Utils.playSound('drop', 0.4);
        
        // 触发投放事件
        this.onDrop && this.onDrop(ball);
        
        // 延迟后允许下次投放
        setTimeout(() => {
            this.isDropping = false;
        }, 500);
        
        return true;
    }

    // 更新物理世界
    update(deltaTime) {
        Matter.Engine.update(this.engine, deltaTime);
        
        // 更新粒子
        Utils.updateParticles(this.particles);
        
        // 检查游戏结束条件
        this.checkGameOver();
        
        // 清理超出边界的球体
        this.cleanupBalls();
    }

    // 检查游戏结束
    checkGameOver() {
        const gameOverLine = GAME_CONFIG.gameplay.gameOverLine;
        
        for (let ball of this.balls) {
            if (ball.body.position.y < gameOverLine) {
                // 检查球体是否静止（避免刚投放就判定游戏结束）
                const velocity = Math.abs(ball.body.velocity.y);
                if (velocity < 0.1) {
                    this.onGameOver && this.onGameOver();
                    return;
                }
            }
        }
    }

    // 清理球体
    cleanupBalls() {
        // 移除超出边界的球体
        for (let i = this.balls.length - 1; i >= 0; i--) {
            const ball = this.balls[i];
            if (ball.body.position.y > GAME_CONFIG.canvas.height + 100) {
                this.removeBall(ball);
            }
        }
        
        // 限制球体数量
        if (this.balls.length > GAME_CONFIG.gameplay.maxBalls) {
            // 移除最老的球体
            const oldestBall = this.balls[0];
            this.removeBall(oldestBall);
        }
    }

    // 使用炸弹道具
    useBomb(x, y, radius = 50) {
        const ballsToRemove = [];
        
        this.balls.forEach(ball => {
            const distance = Utils.distance(
                ball.body.position.x, ball.body.position.y,
                x, y
            );
            
            if (distance <= radius) {
                ballsToRemove.push(ball);
            }
        });
        
        // 移除球体
        ballsToRemove.forEach(ball => {
            // 创建爆炸粒子
            const particles = Utils.createParticles(
                ball.body.position.x, ball.body.position.y,
                ball.color, 8
            );
            this.particles.push(...particles);
            
            this.removeBall(ball);
        });
        
        // 播放爆炸音效
        Utils.playSound('powerup', 0.6);
        Utils.vibrate(100);
        
        return ballsToRemove.length;
    }

    // 使用磁铁道具
    useMagnet(targetLevel) {
        const targetBalls = this.balls.filter(ball => ball.level === targetLevel);
        
        if (targetBalls.length < 2) return false;
        
        // 将相同等级的球体吸引到一起
        const centerX = targetBalls.reduce((sum, ball) => sum + ball.body.position.x, 0) / targetBalls.length;
        const centerY = targetBalls.reduce((sum, ball) => sum + ball.body.position.y, 0) / targetBalls.length;
        
        targetBalls.forEach(ball => {
            const force = {
                x: (centerX - ball.body.position.x) * 0.001,
                y: (centerY - ball.body.position.y) * 0.001
            };
            Matter.Body.applyForce(ball.body, ball.body.position, force);
        });
        
        Utils.playSound('powerup', 0.4);
        return true;
    }

    // 暂停/恢复物理引擎
    pause() {
        this.engine.enabled = false;
    }

    resume() {
        this.engine.enabled = true;
    }

    // 重置游戏
    reset() {
        // 移除所有球体
        this.balls.forEach(ball => {
            Matter.World.remove(this.world, ball.body);
        });
        this.balls = [];
        
        // 清空粒子
        this.particles = [];
        
        // 重置状态
        this.nextBallLevel = Utils.generateRandomBallLevel();
        this.isDropping = false;
    }

    // 获取游戏状态
    getGameState() {
        return {
            ballCount: this.balls.length,
            maxLevel: Math.max(...this.balls.map(ball => ball.level), 0),
            nextBallLevel: this.nextBallLevel,
            isDropping: this.isDropping
        };
    }

    // 设置事件回调
    setEventCallbacks(callbacks) {
        this.onMerge = callbacks.onMerge;
        this.onDrop = callbacks.onDrop;
        this.onGameOver = callbacks.onGameOver;
    }

    // 获取所有球体
    getBalls() {
        return this.balls;
    }

    // 获取粒子
    getParticles() {
        return this.particles;
    }

    // 获取容器边界
    getContainer() {
        return GAME_CONFIG.container;
    }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = PhysicsEngine;
}